package com.qxsx.midi.activity.personal;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.base.BaseActivity;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.utils.Base64Coder;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.SPUtils;
import com.qxsx.midi.utils.Tools;
import com.qxsx.midi.utils.callBackJsonArray;
import com.qxsx.midi.view.CircleImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.text.ParseException;

/**
 * Created by LYJ on 2015/9/8.
 */
public class PersonalImproveNewActivity extends BaseActivity implements View.OnClickListener {
    private CustomProgress customProgress;

    private RelativeLayout rl_icon, rl_name, rl_gender, rl_nationality, rl_nation, rl_birthdate, rl_identity;
    private TextView tv_id, tv_sex, tv_idcard, tv_birth;
    private EditText ed_nation, ed_people;
    private CircleImageView img_head;
    Intent intent = new Intent();
    PopupWindow popupWindow;

    //头像
    private CircleImageView ci_head;

    private Intent dataIntent = null;
    private int sex;
    String userid;
    String midi_id, nickname, real_name, eamil, phone, id_card, nationality, birthday, people;
    String headimg = "";
    Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_improve_n);
        setTitle("完善信息");
        setNavBtn(R.mipmap.back, "", 0, "保存");
        findByID();
        userid = (String) SPUtils.get(AppContext.getContext(), "user_id", "");
        OnAccess(userid);
    }

    private void findByID() {
        rl_icon = (RelativeLayout) findViewById(R.id.improve_icon);
        rl_gender = (RelativeLayout) findViewById(R.id.improve_gender);
        ci_head = (CircleImageView) findViewById(R.id.ci_head);
        tv_id = (TextView) findViewById(R.id.tv_id);
        tv_sex = (TextView) findViewById(R.id.tv_sex);//性别
        tv_idcard = (TextView) findViewById(R.id.tv_idcard);//身份证
        tv_birth = (TextView) findViewById(R.id.tv_birthday);//出生日期
        ed_nation = (EditText) findViewById(R.id.ed_national);//国籍
        ed_people = (EditText) findViewById(R.id.ed_people);//民族

        rl_icon.setOnClickListener(this);
        rl_gender.setOnClickListener(this);

        userid = (String) SPUtils.get(AppContext.getContext(), "user_id", "");


    }

    @Override
    protected void HandleTitleBarEvent(TitleBar component, View v) {
        switch (component) {
            case LEFT:
                finish();
                break;
            case RIGHT:

                LayoutInflater layout = LayoutInflater.from(AppContext.getContext());
                View view = layout.inflate(R.layout.dialog_buy_finish, null);
                dialog = new AlertDialog.Builder(PersonalImproveNewActivity.this).create();
                TextView tv_zhifu = (TextView) view.findViewById(R.id.tv_zhifu);
                tv_zhifu.setText("是否保存？");
                Button btn_see = (Button) view.findViewById(R.id.btn_see);
                btn_see.setText("是");
                Button btn_clance = (Button) view.findViewById(R.id.btn_cancel);
                btn_clance.setText("否");
                btn_clance.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        dialog.dismiss();

                    }
                });
                btn_see.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        uploadPic();
                        dialog.dismiss();
                    }
                });
                DisplayMetrics dm = new DisplayMetrics();
                PersonalImproveNewActivity.this.getWindowManager().getDefaultDisplay().getMetrics(dm);
                int x = dm.widthPixels;// 屏幕的宽
                int y = dm.heightPixels;// 屏幕的高
                dialog = new Dialog(PersonalImproveNewActivity.this, R.style.dialog_finish);
                dialog.getWindow().setLayout((int) (x / 2.2), (int) (y / 1.8));
                dialog.show();
                dialog.setContentView(view);
                dialog.setCancelable(false);


                break;

        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.improve_icon:
                //修改头像
                IconPopWindow();
                break;
            case R.id.improve_gender:
                //性别
                GenderPopWindow();
                break;
//            case R.id.improve_back:
//                //返回
//                intent.setClass(AppContext.getContext(),PersonalDetailsActivity.class);
//                startActivity(intent);
//                finish();
//                break;
        }
    }


    public void IconPopWindow() {
        LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View menuView = mLayoutInflater.inflate(R.layout.fragment_personal_icon_menu, null, true);       //弹出窗口包含的视图
        popupWindow = new PopupWindow(menuView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true); //创建弹出窗口，指定大小
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        menuView.setFocusable(true);
        menuView.setFocusableInTouchMode(true);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.mipmap.study_call_menu_bg));
        menuView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
        menuView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                if (arg1 == KeyEvent.KEYCODE_BACK) {
                    if (popupWindow != null) {
                        popupWindow.dismiss();
                    }
                }
                return false;
            }
        });
        popupWindow.update();
        popupWindow.showAtLocation(findViewById(R.id.improve_icon), Gravity.BOTTOM, 0, 0); // 设置窗口显示的位置

        // 取消
        TextView cancel = (TextView) menuView.findViewById(R.id.btn_personal_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        // 拍照
        TextView photograph = (TextView) menuView.findViewById(R.id.tv_personal_photograph);
        photograph.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                photos();
            }
        });
        //从手机相册选择
        TextView phone = (TextView) menuView.findViewById(R.id.tv_personal_phone);
        phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                picture();
            }
        });
    }


    String Gender = "";

    public void GenderPopWindow() {
        LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View menuView = mLayoutInflater.inflate(R.layout.fragment_personal_gender_menu, null, true);       //弹出窗口包含的视图
        popupWindow = new PopupWindow(menuView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true); //创建弹出窗口，指定大小
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        menuView.setFocusableInTouchMode(true);
        menuView.setFocusable(true);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.mipmap.study_call_menu_bg));
        menuView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
        menuView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                if (arg1 == KeyEvent.KEYCODE_BACK) {
                    if (popupWindow != null) {
                        popupWindow.dismiss();
                    }
                }
                return false;
            }
        });
        popupWindow.update();
        popupWindow.showAtLocation(findViewById(R.id.improve_gender), Gravity.BOTTOM, 0, 0); // 设置窗口显示的位置

        // 保存
        Button save = (Button) menuView.findViewById(R.id.btn_gender_save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int sexx = 0;
                if (Gender.equals("男")) {
                    sexx = 1;
                } else {
                    sexx = 2;
                }
                final int finalSexx = sexx;
                if (finalSexx == 1) {
                    tv_sex.setText("男");
                } else {
                    tv_sex.setText("女");
                }
                popupWindow.dismiss();
            }


        });

        // 男
        final Button btn_man = (Button) menuView.findViewById(R.id.btn_gender_man);
        final Button btn_women = (Button) menuView.findViewById(R.id.btn_gender_women);
        if (sex == 1) {
            btn_man.setTextColor(getResources().getColor(R.color.text_black));
            btn_women.setTextColor(getResources().getColor(R.color.text_greyandwhite));
        } else {
            btn_women.setTextColor(getResources().getColor(R.color.text_black));
            btn_man.setTextColor(getResources().getColor(R.color.text_greyandwhite));
        }
        btn_man.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Gender = "男";
                btn_man.setTextColor(getResources().getColor(R.color.text_black));
                btn_women.setTextColor(getResources().getColor(R.color.text_greyandwhite));
            }
        });
        //女

        btn_women.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Gender = "女";
                btn_women.setTextColor(getResources().getColor(R.color.text_black));
                btn_man.setTextColor(getResources().getColor(R.color.text_greyandwhite));

            }
        });


    }

    private void photos() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, 300);
    }

    private void picture() {
        //启动图库程序
        Intent pictureIntent = new Intent(Intent.ACTION_PICK);
        //设置要操作的数据的类型
        pictureIntent.setType("image/*");
        pictureIntent.putExtra("crop", "true");
        pictureIntent.putExtra("noFaceDetection", true); //取消人脸识别功能
        pictureIntent.putExtra("scale", true);
        pictureIntent.putExtra("return-data", true);

        startActivityForResult(pictureIntent, 400);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param data
     */
    @SuppressWarnings("deprecation")
    private void getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            ci_head.setImageDrawable(drawable);

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_CANCELED) {
            if (300 == requestCode && Activity.RESULT_OK == resultCode) {
                if (data != null) {
                    dataIntent = data;
                    getImageToView(data);
                }
            }
            if (400 == requestCode && Activity.RESULT_OK == resultCode) {
                //获取裁切后的数据
                if (data != null) {
                    dataIntent = data;
                    getImageToView(data);
                }

            }

//            switch (requestCode) {
//                case IMAGE_REQUEST_CODE:
//                    startPhotoZoom(data.getData());
//
//                    break;
//                case CAMERA_REQUEST_CODE:
//                    if (Tools.sdcardIsExist()) {
//
//                        getImageToView(data);
//                        File tempFile = new File(
//                                Environment.getExternalStorageDirectory() + "/"
//                                        + IMAGE_FILE_NAME);
//                        startPhotoZoom(Uri.fromFile(tempFile));
//                    } else {
//                        Toast.makeText(PersonalImproveNewActivity.this, "未找到存储卡，无法存储照片！",
//                                Toast.LENGTH_LONG).show();
//                    }
//                    break;
//                case RESULT_REQUEST_CODE:
//                    if (data != null) {
//                        dataIntent = data;
//                        getImageToView(data);
//                    }
//                    break;
//            }

        }

    }

    void uploadPic() {
        customProgress = CustomProgress.show(PersonalImproveNewActivity.this, "正在保存,请稍后....", true, null);

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            object.put("user_id", userid);
            object.put("real_name", real_name);
            object.put("eamil", eamil);
            object.put("id_card", id_card);
            object.put("nationality", ed_nation.getText().toString());
            object.put("people", ed_people.getText().toString());
            if (tv_sex.getText().toString().equals("男")) {
                object.put("sex", 1 + "");
            } else {
                object.put("sex", 2 + "");
            }
            if (dataIntent != null) {
                Bundle extras = dataIntent.getExtras();
                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                    byte[] bytes = stream.toByteArray();
                    // 将图片流以字符串形式存储下来
                    final String picStr = new String(Base64Coder.encodeLines(bytes));
                    object.put("head_img", picStr);
                }
            }
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        MyNet.doPostJsonArray("106", array, new callBackJsonArray() {
                    @Override
                    public void run(Object code, Object message, JSONArray array) {
                        if (code.toString().equals("401")) {
                            Toast.makeText(AppContext.getContext(), message.toString(), Toast.LENGTH_SHORT).show();
                        } else if (array == null) {
                            Log.w("array", array + "");
                            return;
                        } else {
                            Toast.makeText(AppContext.getContext(), message.toString(), Toast.LENGTH_SHORT).show();
                        }
                        customProgress.dismiss();
                    }
                }

        );

    }


    void OnAccess(String ID) {
        if (ID == "") {
            Log.e("id为空", ID);
            return;
        }
        customProgress = CustomProgress.show(PersonalImproveNewActivity.this, "正在加载中....", true, null);

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            object.put("user_id", ID);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        MyNet.doPostJsonArray("109", array, new callBackJsonArray() {
                    @Override
                    public void run(Object code, Object message, JSONArray array) {
                        //  Log.e("-------------", code.toString());
                        if (!code.toString().equals("200")) {
                            Toast.makeText(AppContext.getContext(), message.toString(), Toast.LENGTH_SHORT).show();
                        } else if (array == null) {
                            Log.w("array", array + "");
                            return;
                        } else {
                            try {
                                JSONObject jsonObject = array.getJSONObject(0);
                                headimg = jsonObject.getString("head_img");
                                midi_id = jsonObject.getString("midi_id");
                                nickname = jsonObject.getString("nickname");
                                real_name = jsonObject.getString("real_name");
                                eamil = jsonObject.getString("eamil");
                                phone = jsonObject.getString("phone");
                                id_card = jsonObject.getString("id_card");
                                nationality = jsonObject.getString("nationality");
                                birthday = jsonObject.getString("birthday");
                                people = jsonObject.getString("people");
                                sex = jsonObject.getInt("sex");

                                tv_id.setText(midi_id);

                                ed_nation.setText(nationality);
                                ed_people.setText(people);
                                if (sex == 1) {
                                    tv_sex.setText("男");
                                } else {
                                    tv_sex.setText("女");

                                }
                                tv_idcard.setText(id_card);
                                if (!id_card.toString().equals("")) {
                                    try {
                                        tv_birth.setText(Tools.GetBirthday(id_card));
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            if (!headimg.equals("") && headimg != null && !headimg.isEmpty()) {
                                MyNet.setNetImage(AppContext.getContext(), ci_head, headimg);
                            }

                        }
                        customProgress.dismiss();
                    }
                }

        );

    }


    @Override
    protected void onResume() {
        super.onResume();
    }


}

